<script setup lang="ts">
import { computed } from "vue";
import icons from "@/config/icons";

defineOptions({
  name: "IconSelect"
});

const emits = defineEmits(["change"]);

const inputValue = defineModel({ type: String });

const isOfflineIcon = computed(() => {
  if (inputValue.value) {
    for (const key in icons) {
      if (key === inputValue.value) {
        return true;
      }
    }
    return false;
  }
  return true;
});

const onChange = (value: string) => {
  emits("change", value);
};
</script>

<template>
  <el-select
    v-model="inputValue"
    placeholder="请选择"
    filterable
    allow-create
    clearable
    @change="onChange"
  >
    <el-option
      v-for="key in Object.keys(icons)"
      :key="key"
      :label="key"
      :value="key"
    >
      <div class="flex items-center">
        <IconifyIconOffline :icon="key" class="icon-size mr-2" />
        <span class="text-color" :class="{ active: key === inputValue }">
          {{ key }}
        </span>
      </div>
    </el-option>
    <template #label="{ value }">
      <div class="flex items-center">
        <IconifyIconOffline
          v-if="isOfflineIcon"
          :icon="value"
          class="icon-size"
        />
        <IconifyIconOnline v-else :icon="value" class="icon-size" />
        <span class="text-color ml-2">{{ value }}</span>
      </div>
    </template>
  </el-select>
</template>

<style lang="scss" scoped>
.icon-size {
  font-size: 18px;
}
.text-color {
  color: var(--pure-theme-menu-text);
  &.active {
    color: inherit;
  }
}
</style>
